<template>
  <div class="container">
      <a-page-header
          title="病人病历管理"
        />
      <div class="condition-container">
        
        <p class="title">Operation：</p>
        <div class="condition-btn-group">
          <a-button type="primary" @click="newRecord" v-if="currentUser._role == 'SYS_ADMIN' || currentUser._role == 'DOCTOR'"> 新增 </a-button>
          <!-- 用户名查找 -->
          用户名：
          <a-input placeholder="搜索用户名" allow-clear @change="onChangeUsername" v-model='searchUsername' style="width:200px"/>
          <!-- 主治医生查找 -->
          主治医生：
          <a-input placeholder="搜索主治医生" allow-clear @change="onChangeDoctor" v-model='doctorUsername' style="width:200px"/>
          <!-- 检查时间查找 -->
          检查时间：
          <a-range-picker @change="onChangeCheckDate"   style="width:200px"/>
          <!-- 检查时间查找 -->
          治疗结束时间：
          <a-range-picker @change="onChangeFinishedDate"   style="width:200px"/>
        </div>
      </div>

      <!--  -->
      <a-table :columns="columns" :data-source="data" class="table-container">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <!-- <span slot="customTitle"><a-icon type="smile-o" /> 用户名</span> -->
        <span slot="tag" slot-scope="tag">
        <a-tag
            :color="tag === false ? 'red' : 'green'"
        >
            {{ tag }}
        </a-tag>
        </span>
        <span slot="action" slot-scope="record">
            <!-- {{record}} -->
            <a-button type="link"  @click="updateCaseRecord(record)" v-if="currentUser._role == 'SYS_ADMIN' || currentUser._role == 'DOCTOR'">病历更新</a-button>
            <!-- <a-button type="link"  @click="showPrecriptionModal(record)">查看处方</a-button> -->
            &nbsp;&nbsp;
            <!-- <a-button type="primary"  @click="exportCaseReport(record)"> 病历报告导出</a-button> -->
        </span>
      </a-table>

      <!-- 新增病历信息表单 -->
      <a-modal
        title="录入病历信息"
        :visible="visible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
         <a-form :form="recordModal" @submit="handleSubmit">
           <!-- 用户名 -->
            <a-form-item v-bind="formItemLayout" label="患者用户名">
              <a-input
                v-decorator="[
                  'username',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者用户名',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
            <!-- 科室 -->
            <a-form-item v-bind="formItemLayout" label="科室">
              <a-input
                v-decorator="[
                  'subject',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入科室',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
           <!-- 检查日期 -->
          <a-form-item label="检查日期" v-bind="formItemLayout" >
            <a-date-picker
              v-decorator="['checkDate', config]"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
            </a-form-item>
           <!-- 治疗结束日期 -->
          <a-form-item label="治疗结束日期" v-bind="formItemLayout">
            <a-date-picker
              v-decorator="['finishedDate', config]"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
            </a-form-item>
           <!-- 症状 -->
            <a-form-item v-bind="formItemLayout" label="症状">
              <a-textarea
              :rows="4"
                v-decorator="[
                  'sympton',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者症状信息',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
           <!-- 主治医生，当前登录用户禁止编辑 -->
          <a-form-item v-bind="formItemLayout" label="主治医生">
              <a-input 
                :disabled='true'
                v-decorator="[
                  'doctor',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请填写主治医生信息',
                      },
                    ],
                  },
                ]"
                placeholder="主治医生"
              />
            </a-form-item>
        </a-form>
      </a-modal>

      <!-- 更新病历信息表单 -->
       <!-- 新增病历信息表单 -->
      <a-modal
        title="录入病历信息"
        :visible="updateVisible"
        :confirm-loading="updateConfirmLoading"
        @ok="handleUpdateOk"
        @cancel="handleUpdateCancel"
      >
         <a-form :form="updateRecordModal" @submit="handleUpdateSubmit">
           <!-- 病历号 -->
           <a-form-item v-bind="formItemLayout" label="病历号">
              <a-input
                disabled
                v-decorator="[
                  'id',
                ]"
              />
            </a-form-item>
           <!-- 用户名 -->
            <a-form-item v-bind="formItemLayout" label="患者用户名">
              <a-input
                v-decorator="[
                  'username',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者用户名',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
            <!-- 科室 -->
            <a-form-item v-bind="formItemLayout" label="科室">
              <a-input
                v-decorator="[
                  'subject',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入科室',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
           <!-- 检查日期 -->
          <a-form-item label="检查日期" v-bind="formItemLayout" >
            <a-date-picker
              v-decorator="['checkDate']"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
            </a-form-item>
           <!-- 治疗结束日期 -->
          <a-form-item label="治疗结束日期" v-bind="formItemLayout">
            <a-date-picker
              v-decorator="['finishedDate']"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
            </a-form-item>
           <!-- 症状 -->
            <a-form-item v-bind="formItemLayout" label="症状">
              <a-textarea
              :rows="4"
                v-decorator="[
                  'sympton',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入患者症状信息',
                      },
                    ],
                  },
                ]"
              />
            </a-form-item>
           <!-- 主治医生，当前登录用户禁止编辑 -->
          <a-form-item v-bind="formItemLayout" label="主治医生">
              <a-input 
                :disabled='true'
                v-decorator="[
                  'doctor',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请填写主治医生信息',
                      },
                    ],
                  },
                ]"
                placeholder="主治医生"
              />
            </a-form-item>
            <!-- 处方号，禁止编辑 -->
          <a-form-item v-bind="formItemLayout" label="处方号">
              <a-input 
                :disabled='true'
                v-decorator="[
                  'prescriptionId',
                  {
                    rules: [
                      {
                        required: true,
                        message: '处方信息',
                      },
                    ],
                  },
                ]"
                placeholder="处方号"
              />
            </a-form-item>
        </a-form>
      </a-modal>

      <!-- 查看处方信息表单 -->
  </div>
</template>

<script>
const columns = [
  // 病历id
  {
    dataIndex: 'id',
    key: 'id',
    // slots: { title: 'customTitle' },
    title: "病例编号",
    scopedSlots: { customRender: 'name' },
  },
  // 患者用户名
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  // 检查日期
  {
      title: '检查日期',
      dataIndex: 'checkDate',
      key: 'checkDate'
  },
  // 治疗结束日期
  {
      title: '治疗结束日期',
      dataIndex: 'finishedDate',
      key: 'finishedDate'
  },
  // 症状
  {
    title: '症状',
    dataIndex: 'sympton',
    key: 'sympton',
  },
  // 主治医生
  {
    title: '主治医生',
    key: 'doctorUsername',
    dataIndex: 'doctorUsername',
    // scopedSlots: { customRender: 'tag' },
  },
  // 检查科目
  {
    title: '科室',
    key: 'subject',
    dataIndex: 'subject',
    // scopedSlots: { customRender: 'action' },
  },
  // 病情处方（显示的是链接）
  // {
  //   title: '病情处方号',
  //   key: 'prescriptionId',
  //   dataIndex: 'prescriptionId',

  // },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];

const data = [
  // {
  //   id: '1',
  //   username: 'aaa',
  //   checkDate: '2022-10-10 10:10:10',
  //   finishedDate: '2022-10-11 10:10:10',
  //   sympton: '感冒发烧流鼻涕',
  //   doctorUsername: 'doctor-tony',
  //   subject: '耳鼻喉科',
  //   prescriptionId: '2',
  // },
  // {
  //   id: '2',
  //   username: 'aaa',
  //   checkDate: '2022-10-10 10:10:10',
  //   finishedDate: '2022-10-11 10:10:10',
  //   sympton: '感冒发烧流鼻涕',
  //   doctorUsername: 'doctor-tony',
  //   subject: '耳鼻喉科',
  //   prescriptionId: '2',
  // },
  // {
  //   id: '3',
  //   username: 'aaa',
  //   checkDate: '2022-10-10 10:10:10',
  //   finishedDate: '2022-10-11 10:10:10',
  //   sympton: '感冒发烧流鼻涕',
  //   doctorUsername: 'doctor-tony',
  //   subject: '耳鼻喉科',
  //   prescriptionId: '2',
  // },
];

import {getAllCaseRecord, addCaseRecord, updateCaseRecord} from "@/api/case_info/patient_record"

export default {
    data(){
        return {
            data,
            cacheData: [],
            columns,
            currentUser: null,
            searchUsername: '',
            doctorUsername: '',
            startCheckDate: '',
            endCheckDate: '',
            startFinishedDate: '',
            endFinishedDate: '',
        
            // 新增病历信息模态框数据
            visible: false,
            confirmLoading: false,
            // recordModal: {},
            formItemLayout: {
              labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
              },
              wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
              },
            },
            config: {
              rules: [{ type: 'object', required: true, message: 'Please select time!' }],
            },

            // 更新病历信息表单数据
            updateConfirmLoading: false,
            updateVisible: false,

        }
    },
    methods: {
        exportCaseReport(record){
            console.log("病历报告导出")
        },
        updateCaseRecord(record){
            // console.log("更新病历信息")
            this.updateRecord(record)
        },
        onChangeUsername(e){
          console.log(this.searchUsername, e)
          this.data = this.cacheData.filter(item=>{
            return item.username.indexOf(this.searchUsername) != -1
          })
        },
        onChangeCheckDate(date, dateString){
          console.log(date, dateString)
          if(!date[0] || ! date[1])return
          this.startCheckDate = date[0]._d
          this.endCheckDate = date[1]._d
          this.data = this.cacheData.filter(item=>{
            if(!this.startCheckDate || !this.endCheckDate)return true
            return new Date(item.checkDate) >= this.startCheckDate
             && new Date(item.checkDate) <= this.endCheckDate
          });
        },
        onChangeFinishedDate(date, dateString){
          console.log(date, dateString)
          if(!date[0] || !date[1]){
            this.data = this.cacheData.filter(item=>{return true;})
            return
          }
          this.startFinishedDate = date[0]._d
          this.endFinishedDate = date[1]._d
          this.data = this.cacheData.filter(item=>{
            if(!this.startFinishedDate || !this.endFinishedDate)return true
            return new Date(item.finishedDate) >= this.startFinishedDate
             && new Date(item.finishedDate) <= this.endFinishedDate
          });
        },
        onChangeDoctor(e){
          console.log(e)
          this.data = this.cacheData.filter(item=>{
            return item.doctorUsername.indexOf(this.doctorUsername) != -1 
          })
        },
        handleCancel(){
          console.log("cancel");
          this.visible = false;
        },
        handleOk(e){
          // 验证表达数据合法性
          // console.log(this.recordModal)
          this.recordModal.validateFieldsAndScroll((err, values) => {
            if (!err) {
              
              // 时间转为时间戳进行存储
              values['checkDate'] = values['checkDate']._d.getTime()
              values['finishedDate'] = values['finishedDate']._d.getTime()
              // console.log(values['checkDate']._d)
              // console.log('Received values of form: ', values);
              // 提交数据
              addCaseRecord(values)
              .then(data=>{
                this.$message.success("数据提交成功")
              })
              .catch(err=>{
                this.$message.error("数据提交错误")
              })
              this.visible = false;
              this.confirmLoading = false;
              this.getAllCaseRecords()
            }
          });
          // console.log("ok")
          
        },
        newRecord(){
          this.visible = true
          this.$nextTick(() => {
            this.recordModal.setFieldsValue({
              doctor: this.currentUser.username,
            })});
        },
        getCurrentLoginUsername(){
          // var currentUser =  localStorage.getItem("currentLoginUser")
          this.currentUser = localStorage.getItem("currentLoginUser")
          if(this.currentUser == null || this.currentUser == undefined || this.currentUser == '' || this.currentUser == 'null'){
            return null
          }
          return JSON.parse(this.currentUser).username;
        },
        // 获取病历信息记录
        getAllCaseRecords(){
          getAllCaseRecord()
          .then(data=>{
            // console.log("record data: ", data)
            if(data.code != 200){
              this.$message.error("error: " + data.message)
              return;
            }
            // 智能合约中返回的数组格式的对象
            var ret = []
            // console.log("data: ", data.data.length
            // )
            for(var i = 0; i < data.data.length; i++){
              var d = data.data[i]
              // console.log("d: ", d)
              var t = {}
              t['id'] = d[0];
              t['username'] = d[1];
              t['checkDate'] = this.$moment(new Date(Number(d[2]))).format('YYYY-MM-DD HH:mm:ss');
              t['finishedDate'] = this.$moment(new Date(Number(d[3]))).format('YYYY-MM-DD HH:mm:ss');
              t['sympton'] = d[4];
              t['doctorUsername'] = d[5];
              t['prescriptionId'] = d[6];
              t['subject'] = d[7];
              // console.log("t: ", t)
              ret.push(t)
            }
            this.data = ret;
            this.cacheData = this.data;
            console.log(this.data)
          })
          .catch(err=>{
            console.log(err)
            // this.$message.error("获取病历信息出错")
          })
        },

        // 更新表单
        updateRecord(record){
          this.updateVisible = true;
          // console.log("record: ", record)
          // 设置参数默认值
          this.$nextTick(() => {
            this.updateRecordModal.setFieldsValue({
              // doctor: this.currentUser.username,
              id: record.id,
              username: record.username,
              checkDate: record.checkDate,
              finishedDate: record.finishedDate,
              sympton: record.sympton,
              doctor: record.doctorUsername,
              subject: record.subject,
              prescriptionId: record.prescriptionId,
            })});
        },
        handleUpdateOk(e){
            this.updateRecordModal.validateFieldsAndScroll((err, values) => {
              if (!err) {
                console.log('Received values of form: ', values);
                // 时间转为时间戳进行存储
                // 更新则更改
                if(values['checkDate']._d != undefined){
                   values['checkDate'] = values['checkDate']._d.getTime()
                }
                else{
                  values['checkDate'] = new Date(values['checkDate']).getTime()
                }
                if(values['finishedDate']._d != undefined){
                  values['finishedDate'] = values['finishedDate']._d.getTime()
                }else{
                  values['finishedDate'] = new Date(values['finishedDate']).getTime()
                }
                values['id'] = Number(values['id'])
                values['prescriptionId'] = Number(values['prescriptionId'])
                // console.log(values['checkDate']._d)
                console.log('Received values of form: ', values);
                // 提交数据
                updateCaseRecord(values)
                .then(data=>{
                  this.$message.success("数据提交成功")
                })
                .catch(err=>{
                  this.$message.error("数据提交错误")
                })
                this.updateVisible = false;
                this.updateConfirmLoading = false;
                this.getAllCaseRecords()
              }
            });
            console.log("ok")
        },
        handleUpdateCancel(){
          this.updateVisible = false
        },
        handleUpdateSubmit(){

        },
        handleSubmit(){

        },
        showPrecriptionModal(){

        }

        // 条件查询

    },
    beforeCreate(){
      this.recordModal = this.$form.createForm(this, { name: 'recordModal' });
      this.updateRecordModal = this.$form.createForm(this, { name: 'updateRecordModal' });
      // var currentUser =  localStorage.getItem("currentLoginUser")
      // var doctor = JSON.parse(currentUser).username;
      // this.recordModal.setFieldsValue({"doctor": doctor})
      // console.log(this.recordModal)
    },
    created(){
      this.currentUser =  JSON.parse(localStorage.getItem("currentLoginUser"))
      // console.log(this.currentUser)
      // 获取病历信息
      this.getAllCaseRecords()
    },
    mounted(){
      // this.recordModal.setFieldsValue({doctor: this.currentUser.username})
    }
}
</script>

<style lang="less" scoped>
.container{
    margin: auto;
    width: 90%;
    min-height: 700px;
    // margin-top: 30px;
    margin-bottom: 30px;
    background-color: aliceblue;

}

.table-container{
    min-height: 700px;
}

.condition-container{
  width: 100%;
  min-height: 80px;
  background-color: antiquewhite;
  margin-bottom: 10px;
  padding: 5px;
}

.title{
  font-size: 20px;
  font-weight: bold;
}

.condition-btn-group{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>